package com.xm.controller;

import com.alibaba.excel.EasyExcel;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ramostear.captcha.HappyCaptcha;
import com.ramostear.captcha.common.Fonts;
import com.ramostear.captcha.support.CaptchaStyle;
import com.xm.pojo.User;
import com.xm.service.UserService;
import com.xm.until.LayuiTypeJson;
import com.xm.until.UploadUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 表现层（web层）：接收前端传递的数据，返回数据给前端
 *
 * @Controller，@RestController，@Service，@Repository创建对象所需的注解
 */
@RestController//返回json类型的数据
@RequestMapping("user")//一级访问路径
public class UserController {
    @Autowired //自动装配，将spring容器中的PatientService类型对象，赋值给patientService
    private UserService userService;

    @RequestMapping("findAll")//查找所有用户
    public Map findAll() {
        List<User> userList = userService.findAll();
        HashMap<String, Object> map = new HashMap<>();
        map.put("code", 0);
        map.put("msg", "success");
        map.put("count", 1000);
        map.put("data", userList);
        return map;
    }

    @RequestMapping("findByPage")//分页显示接口
    public Map findByPage(@RequestParam(defaultValue = "") String v,
                          @RequestParam(defaultValue = "") String c,
                          @RequestParam(value = "page", required = false, defaultValue = "1") Integer pageNum,
                          @RequestParam(value = "limit", required = false) Integer pageSize) {
        List<User> list = null;
        //System.out.println(v+"--------------------------------------------------------------");
        //System.out.println(c+"--------------------------------------------------------------");
        if (v.equals("")) {
            PageHelper.startPage(pageNum, pageSize);
            list = userService.findAll();
            PageInfo<Object> pageInfo = new PageInfo<Object>(list);
            HashMap<String, Object> map = new HashMap<>();
            map.put("code", 0);
            map.put("msg", "success");
            map.put("count", pageInfo.getTotal());//总记录数
            map.put("data", pageInfo.getList());//分页数据
            return map;
        }
        if (!v.equals("")) {
            if (c.equals("1")) {
                PageHelper.startPage(pageNum, pageSize);
                list = userService.findById(v);
                PageInfo<Object> pageInfo = new PageInfo<Object>(list);
                HashMap<String, Object> map = new HashMap<>();
                map.put("code", 0);
                map.put("msg", "success");
                map.put("count", pageInfo.getTotal());//总记录数
                map.put("data", pageInfo.getList());//分页数据
                return map;
            }
            if (c.equals("2")) {
                PageHelper.startPage(pageNum, pageSize);
                list = userService.findByUsername(v);
                PageInfo<Object> pageInfo = new PageInfo<Object>(list);
                HashMap<String, Object> map = new HashMap<>();
                map.put("code", 0);
                map.put("msg", "success");
                map.put("count", pageInfo.getTotal());//总记录数
                map.put("data", pageInfo.getList());//分页数据
                return map;
            }
            if (c.equals("3")) {
                PageHelper.startPage(pageNum, pageSize);
                list = userService.findByNick(v);
                PageInfo<Object> pageInfo = new PageInfo<Object>(list);
                HashMap<String, Object> map = new HashMap<>();
                map.put("code", 0);
                map.put("msg", "success");
                map.put("count", pageInfo.getTotal());//总记录数
                map.put("data", pageInfo.getList());//分页数据
                return map;
            }
            if (c.equals("4")) {
                PageHelper.startPage(pageNum, pageSize);
                list = userService.findByPhone(v);
                PageInfo<Object> pageInfo = new PageInfo<Object>(list);
                HashMap<String, Object> map = new HashMap<>();
                map.put("code", 0);
                map.put("msg", "success");
                map.put("count", pageInfo.getTotal());//总记录数
                map.put("data", pageInfo.getList());//分页数据
                return map;
            } else {
                PageHelper.startPage(pageNum, pageSize);
                list = userService.findAll();
                PageInfo<Object> pageInfo = new PageInfo<Object>(list);
                HashMap<String, Object> map = new HashMap<>();
                map.put("code", 0);
                map.put("msg", "success");
                map.put("count", pageInfo.getTotal());//总记录数
                map.put("data", pageInfo.getList());//分页数据
                return map;
            }
        } else {
            PageHelper.startPage(pageNum, pageSize);
            list = userService.findAll();
            PageInfo<Object> pageInfo = new PageInfo<Object>(list);
            HashMap<String, Object> map = new HashMap<>();
            map.put("code", 0);
            map.put("msg", "success");
            map.put("count", pageInfo.getTotal());//总记录数
            map.put("data", pageInfo.getList());//分页数据
            return map;
        }
    }

    @RequestMapping("findDeletedPage")//查找被逻辑删除的数据
    public Map findDeletedPage(
            @RequestParam(value = "page", required = false, defaultValue = "1") Integer pageNum,
            @RequestParam(value = "limit", required = false) Integer pageSize
    ) {
        //设置分页参数
        PageHelper.startPage(pageNum, pageSize);
        //紧跟在PageHelper.startPage（）后才会被分页
        List<User> userList = userService.findDeleted();
        //创建PageInfo对象
        PageInfo<Object> pageInfo = new PageInfo<Object>(userList);
        HashMap<String, Object> map = new HashMap<>();
        map.put("code", 0);
        map.put("msg", "success");
        map.put("count", pageInfo.getTotal());//总记录数
        map.put("data", pageInfo.getList());//分页数据
        return map;
    }

    @RequestMapping("add")//添加接口
    public void add(User user, HttpServletRequest request, HttpServletResponse response) throws IOException {
        userService.add(user);
        //添加完之后，跳转到首页
        response.sendRedirect(request.getContextPath() + "/userAdd.html");
    }

    @RequestMapping("logicDelete")//逻辑删除接口
    public String logicDelete(User user) {
        //System.out.println(medical);
        userService.logicDelete(user);
        return "success";
    }

    @RequestMapping("updateUser")//编辑接口
    public String updateUser(User user) {
        userService.updateUser(user);
        return "success";
    }

    @RequestMapping("batchDel")//批量物理删除接口
    public String batchDel(Integer[] ids) {
        userService.batchDel(ids);
        return "success";
    }

    @RequestMapping("wirteExcel")//导出接口
    public void wirteExcel(Integer[] ids, HttpServletResponse response) throws IOException {
        //System.out.println(Arrays.toString(ids));

        if (ids.length > 0) {
            List<User> userList = userService.findByIds(ids);
            //System.out.println(medicalList);
            //System.out.println("系统时间：" + System.currentTimeMillis() );
            String time = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
            //System.out.println(time);
            //以下载的方式打开
            String fileName = "user-" + time + ".xlsx";
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
            //获取输出流
            ServletOutputStream outputStream = response.getOutputStream();
            //流的方式写入
            EasyExcel.write(outputStream, User.class).sheet("医护人员列表").doWrite(userList);
        } else {
            String time = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
            List<User> userList = userService.findAll();
            String fileName = "user-" + time + ".xlsx";
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
            ServletOutputStream outputStream = response.getOutputStream();
            EasyExcel.write(outputStream, User.class).sheet("医护人员列表").doWrite(userList);
        }

    }

    @RequestMapping("writeAll")//全部导出
    public void writeAll(HttpServletResponse response) throws IOException {
        String time = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        List<User> userList = userService.findAll();
        String fileName = "user-" + time + ".xlsx";
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
        ServletOutputStream outputStream = response.getOutputStream();
        EasyExcel.write(outputStream, User.class).sheet("医护人员列表").doWrite(userList);
    }

    @RequestMapping("upload")//导入
    public Map upload(MultipartFile file) {

        HashMap<String, Object> map = new HashMap<>();

        if (file != null) {
            //System.out.println(file.getOriginalFilename());//输出上传的文件名

            //调用上传的方法
            userService.upload(file);

            map.put("code", 0);
            map.put("msg", "success");

        }

        return map;
    }

    @RequestMapping("restoreById")//恢复数据接口
    public String restoreById(User user) {
        //System.out.println(user);
        userService.restoreById(user);
        return "success";
    }

    @RequestMapping("batchRes")//批量恢复接口
    public String batchRes(Integer[] ids) {
        userService.batchRes(ids);
        return "success";
    }

    @RequestMapping("deleteById")//删除患者
    public String deleteById(String id) {
        userService.deleteById(id);
        return "ok";
    }
    @RequestMapping("upload image")
    @ResponseBody
    public Map<String,Object> uploadimage(@RequestParam("file") MultipartFile file,HttpServletRequest request) throws Exception{
        Map<String,Object> map = new HashMap<String,Object>();
        String imagePath = UploadUtil.upload(file);//UploadUtil是一个工具类，返回的是图片的存储路径
        System.out.println(imagePath);
        if(imagePath!=null){
            map.put("code", 1);
            map.put("msg", "上传成功");
            map.put("src", imagePath);
        }else{
            map.put("code", 0);
            map.put("msg", "上传失败");
        }
        return map;
    }
    @RequestMapping("getuserNum")//二级访问路径，获取确诊人数
    public Integer getuserNum() {
        Integer userNum = userService.getuserNum();
        return userNum;
    }

    @RequestMapping("getImg")
    public String getImg(){
        String urls = userService.getImg();
        return urls;
    }
}
